package com.ycy.listener;

import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.impl.cfg.TransactionState;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.history.HistoricProcessInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class TransactionCommittedFlowableListener implements FlowableEventListener {

  Logger logger = LoggerFactory.getLogger(this.getClass());

  private ProcessEngine processEngine;

  public TransactionCommittedFlowableListener() {
  }

  @Override
  public void onEvent(FlowableEvent event) {
    logger.info("committed 通知事件 --> {}", event);
    List<HistoricProcessInstance> lists = processEngine.getHistoryService()
            .createHistoricProcessInstanceQuery()
            .orderByProcessInstanceStartTime()
            .desc()
            .list();

    for (HistoricProcessInstance list : lists) {
      System.out.println(list);
    }
    //测试结果 如果抛出异常 异常 不会触发回滚，因为这个时候 事务已经提交。
    if(true){
      throw new RuntimeException("committed 触发运行时异常，是否能回滚");
    }
  }

  @Override
  public boolean isFailOnException() {
    return true;
  }

  @Override
  public boolean isFireOnTransactionLifecycleEvent() {
    return true;
  }

  @Override
  public String getOnTransaction() {
    return TransactionState.COMMITTED.name();
  }

  public Logger getLogger() {
    return logger;
  }

  public void setLogger(Logger logger) {
    this.logger = logger;
  }

  public ProcessEngine getProcessEngine() {
    return processEngine;
  }

  public void setProcessEngine(ProcessEngine processEngine) {
    this.processEngine = processEngine;
  }
}
